const pestHistoryManager = {
    currentPage: 1,
    pageSize: 6, // Default value, will be calculated
    totalCount: 0,
    historyData: [], // 存储从接口或模拟文件获取的原始数据
    filteredData: [], // 存储筛选后的数据
    pagination: null,
    imageModal: null,
    modalImage: null,
    isAndroidEnvironment: false,

    init() {
        this.historyGrid = document.getElementById('history-grid');
        if (!this.historyGrid) return;

        // 初始化模态框元素
        this.imageModal = document.getElementById('image-modal');
        this.modalImage = document.getElementById('modal-image');
        this.initModalEvents();

        // 初始化筛选器UI元素
        this.initFilterControls();

        // 检查是否应该使用模拟数据
        this.useMockData = typeof shouldUseMockData === 'function' ? shouldUseMockData() : (window.AppConfig ? AppConfig.useMockData : true);
        console.log(`数据模式: ${this.useMockData ? '模拟数据' : '真实数据'}`);

        // 初始化Android接口（无论使用什么数据，都初始化接口）
        if (isAndroidWebView()) {
            initAndroidInterface('虫情检测页面');
        }

        // 加载历史数据
        this.loadHistoryData();
    },
    
    // 初始化筛选器控件和事件
    initFilterControls() {
        this.startDateInput = document.getElementById('start-date');
        this.endDateInput = document.getElementById('end-date');
        this.channelSelect = document.getElementById('channel-select');
        this.detectionStatusSelect = document.getElementById('detection-status');
        this.pestTypeSelect = document.getElementById('pest-type-select');
        this.searchBtn = document.getElementById('search-btn');
        this.resetBtn = document.getElementById('reset-btn');

        this.searchBtn.addEventListener('click', () => this.filterAndDisplayData());
        this.resetBtn.addEventListener('click', () => this.resetFilters());
    },
    
    // 获取历史数据
    loadHistoryData() {
        // 如果配置为使用模拟数据，直接使用模拟数据
        if (this.useMockData) {
            console.log('根据配置使用模拟数据');
            this.fallbackToMockData();
            return;
        }
        
        // 显示加载状态
        this.showLoading();
        
        // 调用Android接口获取数据
        callAndroidMethodAsync('getPestDetectionHistory', {})
            .then(response => {
                console.log('获取虫情检测历史数据:', response);
                if (response && response.success) {
                    // 处理返回的数据
                    this.processApiData(response.data);
                } else {
                    // 处理错误
                    console.error('获取虫情检测历史数据失败:', response ? response.message : '未知错误');
                    this.showError('获取数据失败，请稍后再试');
                    // 使用模拟数据作为后备
                    this.fallbackToMockData();
                }
            })
            .catch(error => {
                console.error('调用Android接口出错:', error);
                this.showError('系统错误，请稍后再试');
                // 使用模拟数据作为后备
                this.fallbackToMockData();
            })
            .finally(() => {
                this.hideLoading();
            });
    },
    
    // 处理从API获取的数据
    processApiData(data) {
        let records = [];
        if (Array.isArray(data)) {
            records = data;
        } else if (data && Array.isArray(data.list)) {
            records = data.list;
        } else if (data && Array.isArray(data.records)) {
            records = data.records;
        }

        if (records.length > 0) {
            this.historyData = records.map((item, index) => ({
                id: item.id || `record-${index + 1}`,
                timestamp: item.createTime || item.timestamp || new Date().toLocaleString(),
                channel: item.channel, // 假设API返回channel字段
                imageUrl: item.imageUrl || item.image || '',
                summary: Array.isArray(item.pestResults) ? item.pestResults.map(pest => ({
                    name: pest.pestName || pest.name || '未知',
                    count: pest.count || 1
                })) : []
            }));
            this.filterAndDisplayData(); // 初始加载时进行一次默认筛选和显示
        } else {
            this.showEmpty('暂无虫情检测记录');
        }
    },
    
    // 回退到模拟数据
    fallbackToMockData() {
        console.log('使用模拟数据');
        if (typeof MOCK_PEST_HISTORY === 'undefined' || !MOCK_PEST_HISTORY) {
            console.error('模拟数据不可用');
            this.showEmpty('无法加载虫情历史数据');
            return;
        }

        this.historyData = MOCK_PEST_HISTORY;
        this.totalCount = this.historyData.length;

        // 渲染一张卡片以确保我们可以测量它
        this.renderHistory(this.historyData.slice(0, 1));

        // 延迟布局计算和完整加载以允许DOM更新
        setTimeout(() => {
            this.calculateAndSetLayout();
            this.loadHistory(1); // 使用正确的页面大小加载第1页

            window.addEventListener('resize', this.debounce(() => {
                this.calculateAndSetLayout();
                this.loadHistory(1); // 在调整大小时从第1页重新加载
            }, 250));
        }, 0);

        this.populatePestFilter();
        this.filterAndDisplayData();
    },
    
    // 显示加载状态
    showLoading() {
        this.historyGrid.innerHTML = '<div class="loading-indicator">正在加载数据...</div>';
    },
    
    // 隐藏加载状态
    hideLoading() {
        // 加载完成后会调用renderHistory，所以这里不需要清除内容
    },
    
    // 显示错误信息
    showError(message) {
        this.historyGrid.innerHTML = `<div class="error-message">${message}</div>`;
    },
    
    // 显示空数据提示
    showEmpty(message) {
        this.historyGrid.innerHTML = `<div class="empty-data-message">${message || '暂无数据'}</div>`;
    },
    
    // 初始化模态框事件
    initModalEvents() {
        if (!this.imageModal) return;
        
        // 关闭按钮点击事件
        const closeButton = this.imageModal.querySelector('.close-modal');
        if (closeButton) {
            closeButton.addEventListener('click', () => this.closeModal());
        }
        
        // 点击模态框背景关闭
        this.imageModal.addEventListener('click', (e) => {
            if (e.target === this.imageModal) {
                this.closeModal();
            }
        });
    },
    
    // 打开模态框显示图片
    openModal(imageUrl) {
        if (!this.imageModal || !this.modalImage) return;
        
        this.modalImage.src = imageUrl;
        this.imageModal.classList.add('active');
    },
    
    // 关闭模态框
    closeModal() {
        if (!this.imageModal) return;
        
        this.imageModal.classList.remove('active');
    },
    
    calculateAndSetLayout() {
        if (this.filteredData.length === 0) {
            this.pageSize = 6;
            document.documentElement.style.setProperty('--pest-card-height', `240px`);
            return;
        }

        // 渲染一张卡片以测量尺寸
        this.renderHistory(this.filteredData.slice(0, 1));
        const firstCard = this.historyGrid.querySelector('.history-card');
        if (!firstCard) return;

        // 设置更合适的卡片高度，确保能够显示所有内容
        const cardHeight = 220; // 从200px增加到220px，确保有足够空间显示多种虫类
        document.documentElement.style.setProperty('--pest-card-height', `${cardHeight}px`);

        // 计算容器尺寸
        const gridContainer = this.historyGrid;
        const containerWidth = gridContainer.offsetWidth;
        
        // 计算可用的垂直空间
        // 整个页面高度减去头部、搜索区域和分页控件的高度
        const mainElement = document.querySelector('main');
        const searchContainer = document.querySelector('.search-container');
        const paginationContainer = document.getElementById('pest-history-pagination');
        
        // 获取这些元素的高度，如果元素不存在则使用估计值
        const searchHeight = searchContainer ? searchContainer.offsetHeight : 120;
        const paginationHeight = paginationContainer ? paginationContainer.offsetHeight : 50;
        const headerHeight = 64; // 估计的头部高度
        
        // 计算可用的容器高度
        const viewportHeight = window.innerHeight;
        const availableHeight = viewportHeight - headerHeight - searchHeight - paginationHeight - 40; // 40px作为边距
        
        // 确保至少有足够的高度显示一行卡片
        const containerHeight = Math.max(availableHeight, cardHeight + 20);

        // 计算网格布局
        const gap = 16;
        const minCardWidth = 280;
        const columns = Math.floor((containerWidth + gap) / (minCardWidth + gap)) || 1;
        const rows = Math.max(2, Math.floor((containerHeight + gap) / (cardHeight + gap))) || 1;
        
        // 设置每页显示的卡片数量
        this.pageSize = columns * rows;
        
        console.log(`布局计算: ${columns} 列 x ${rows} 行 = ${this.pageSize} 每页, 容器高度: ${containerHeight}px`);
    },

    loadHistory(page) {
        this.currentPage = page;
        const start = (page - 1) * this.pageSize;
        const end = start + this.pageSize;
        const pageRecords = this.filteredData.slice(start, end);

        if (this.filteredData.length > 0) {
            this.renderHistory(pageRecords);
        } else {
            this.showEmpty('没有符合条件的记录');
        }
        this.updatePagination();
    },

    renderHistory(records) {
        this.historyGrid.innerHTML = '';
        if (records.length === 0) {
            this.historyGrid.innerHTML = '<p class="empty-data-message">当前页无数据</p>';
            return;
        }
        records.forEach(record => {
            const card = this.createHistoryCard(record);
            this.historyGrid.appendChild(card);
        });
    },

    createHistoryCard(record) {
        const card = document.createElement('div');
        card.className = 'history-card';

        let summary = record.summary;
        let noDetection = false;
        
        // 检查是否未识别到虫害
        if (!summary || summary.length === 0 || (summary.length === 1 && summary[0].name === '未识别到虫害')) {
            summary = [{ name: '未识别到虫害', count: 0 }];
            noDetection = true;
        }

        const summaryHtml = summary
            .map(item => {
                if (item.count === 0) {
                    return `<span class="pest-result-item ${noDetection ? 'no-detection' : ''}">${item.name}</span>`;
                }
                return `<span class="pest-result-item">${item.name}: ${item.count}只</span>`;
            })
            .join('');

        card.innerHTML = `
            <div class="card-image-container">
                <img src="${record.imageUrl}" alt="虫情监测图像 ${record.timestamp}" class="card-image" loading="lazy">
            </div>
            <div class="card-content">
                <div class="timestamp">${record.timestamp}</div>
                <div class="results-summary">${summaryHtml}</div>
            </div>
        `;

        card.querySelector('.card-image-container').addEventListener('click', (e) => {
            e.stopPropagation();
            this.openModal(record.imageUrl);
        });

        return card;
    },
    
    updatePagination() {
        const paginationContainer = document.getElementById('pest-history-pagination');
        if (!paginationContainer) return;

        // 确保 PaginationComponent 已加载
        if (typeof PaginationComponent === 'undefined') {
            console.error('PaginationComponent 未加载，无法更新分页。');
            return;
        }

        if (!this.pagination) {
            // 如果分页器不存在，则创建一个新的实例
            const options = {
                containerId: 'pest-history-pagination',
                currentPage: this.currentPage,
                totalCount: this.totalCount,
                pageSize: this.pageSize,
                theme: 'compact',
                onPageChange: (page) => this.loadHistory(page)
            };
            this.pagination = PaginationComponent.create(options);
        } else {
            // 如果分页器已存在，则更新其选项
            this.pagination.update({
                pageSize: this.pageSize,
                totalCount: this.totalCount,
                currentPage: this.currentPage
            });
        }
    },

    // 筛选数据并更新显示
    filterAndDisplayData() {
        const filters = {
            startDate: this.startDateInput.value,
            endDate: this.endDateInput.value,
            // channel: this.channelSelect.value,
            detectionStatus: this.detectionStatusSelect.value,
            pestType: this.pestTypeSelect.value
        };

        console.log('应用筛选条件:', filters);

        this.filteredData = this.historyData.filter(record => {
            // 安全检查：确保 record 是一个有效的对象
            if (!record) {
                return false;
            }

            // 筛选时间
            const recordDate = new Date(record.timestamp);
            if (filters.startDate && recordDate < new Date(filters.startDate)) {
                return false;
            }
            if (filters.endDate && recordDate > new Date(filters.endDate)) {
                return false;
            }

            // 筛选通道
            if (filters.channel && record.channel.toString() !== filters.channel) {
                return false;
            }

            // 筛选识别状态
            if (filters.detectionStatus) {
                const hasPests = record.summary && record.summary.length > 0;
                if (filters.detectionStatus === 'detected' && !hasPests) {
                    return false;
                }
                if (filters.detectionStatus === 'not-detected' && hasPests) {
                    return false;
                }
            }
            
            // 新增：筛选虫类
            if (filters.pestType) {
                if (!hasPests || !record.summary.some(pest => pest.name === filters.pestType)) {
                    return false;
                }
            }

            return true;
        });

        this.totalCount = this.filteredData.length;
        console.log(`筛选后剩余 ${this.totalCount} 条数据`);

        // 初始化或更新布局并加载第一页
        this.calculateAndSetLayout();
        this.loadHistory(1);
    },

    // 重置筛选条件
    resetFilters() {
        this.startDateInput.value = '';
        this.endDateInput.value = '';
        this.channelSelect.value = '';
        this.detectionStatusSelect.value = '';
        this.pestTypeSelect.value = '';
        this.filterAndDisplayData();
    },

    // 动态填充虫类筛选器
    populatePestFilter() {
        if (!this.pestTypeSelect) return;

        const pestTypes = new Set();
        this.historyData.forEach(record => {
            if (record.summary) {
                record.summary.forEach(pest => pestTypes.add(pest.name));
            }
        });

        // 清空现有选项（除了第一个"所有虫类"）
        this.pestTypeSelect.innerHTML = '<option value="">所有虫类</option>';

        pestTypes.forEach(pestName => {
            if(pestName !== '未识别到虫害') {
                const option = document.createElement('option');
                option.value = pestName;
                option.textContent = pestName;
                this.pestTypeSelect.appendChild(option);
            }
        });
    },

    // Utility function to debounce resize events
    debounce(func, wait) {
        let timeout;
        return function(...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    }
};

// 导出为全局变量
window.pestHistoryManager = pestHistoryManager;

// 将所有初始化逻辑移入 DOMContentLoaded 回调
document.addEventListener('DOMContentLoaded', () => {
    // 确保 pestHistoryManager 存在
    if (window.pestHistoryManager) {
        pestHistoryManager.init();
        
        // 添加窗口大小调整事件监听
        window.addEventListener('resize', pestHistoryManager.debounce(() => {
            pestHistoryManager.calculateAndSetLayout();
            pestHistoryManager.loadHistory(1);
        }, 250));
    }
});